
<template>
  <div>
    <van-nav-bar title="黑马头条-登录" placeholder />
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.mobile"
        required
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          {
            required: true,
            message: '请填写正确的手机号',
            pattern: /^1[3-9]\d{9}$/,
          },
        ]"
      />
      <van-field
        v-model="form.code"
        required
        type="password"
        name="code"
        label="密码"
        placeholder="请输入密码"
        :rules="[
          {
            required: true,
          message: '请填写正确的密码',
          pattern: /^\d{6}$/
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button
        round
        block
        :disabled='isLogin'
        :loading ='isLogin'
        type="info"
        native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginApi } from '@/api'
import { setToken } from '@/utils/token'
import { Toast } from 'vant'
export default {
  data () {
    return {
      form: {
        mobile: '15682942397',
        code: '246810'
      },
      isLogin: false // 加载禁用状态
    }
  },
  methods: {
    async onSubmit (values) {
      // 点击禁用按钮 请求完成后不论成功失败都解除禁用
      // 防止用户连点
      this.isLogin = true
      // console.log('submit', values)
      try {
        const res = await loginApi({
          // mobile: this.form.mobile,
          // code: this.form.code,
          // 简写
          ...this.form
        })
        console.log(res)
        // console.log(res.data.data.token)
        // 存储token到本地
        setToken(res.data.data.token)
        localStorage.setItem('refresh_token', res.data.data.refresh_token)
        this.isLogin = false
        Toast.success('登录成功')
        // this.$notify({ type: 'success', message: '登录成功' })
        // 登录成功跳转页面
        this.$router.push('/layout/home')
      } catch (err) {
        this.isLogin = false
        this.$notify({ type: 'danger', message: '登陆失败' })
        console.error(err)
      }
    }
  }
}
</script>

<style scoped lang='less'>
</style>
